package com.chinackts.common.okhttp;

import com.chinackts.common.utils.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.BeanUtils;

import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;

/**
 * @author Lianhong
 * @since 2022/3/15
 */
@Slf4j
public class RetryInterceptor implements Interceptor {

    public int maxRetryCount;
    private int count = 0;

    public RetryInterceptor(int maxRetryCount) {
        this.maxRetryCount = maxRetryCount;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        return retry(chain);
    }

    public Response retry(Chain chain) {
        Response response = null;
        Request request = chain.request();
        Request.Builder builder = request.newBuilder();
        builder.header("Connection", "close");
        try {
            response = chain.proceed(builder.build());
            while (response == null || (!response.isSuccessful() && count < maxRetryCount)) {
                count++;
                response = retry(chain);
            }
        } catch (Exception e) {
            if(e.getCause() instanceof SocketException
                    || e.getCause() instanceof SSLException
                    || e.getCause() instanceof SocketTimeoutException
                    || e.getCause() instanceof SSLHandshakeException) {
                log.info("okhttp请求重试异常, 删除IP: {}", e.getMessage());
                SpringUtil.getBean(ProxyWeightedSelector.class).delProxyIP();
            }
            while (count < maxRetryCount) {
                count++;
                response = retry(chain);
            }
        }
        return response;
    }
}
